const mysql = require('mysql2/promise');
const TableAdapter = require('./table-adapter');

// 数据库连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'community_service_platform',
  port: 3306
};

async function testMapping() {
  try {
    console.log('🔍 测试字段映射...');
    
    // 创建连接
    const connection = await mysql.createConnection(dbConfig);
    console.log('✅ 数据库连接成功！');
    
    const tableAdapter = new TableAdapter();
    
    // 查找shared_items表
    const tableName = await tableAdapter.findTableName(connection, 'idleItems');
    console.log(`📋 找到表: ${tableName}`);
    
    // 获取字段映射
    const fieldMapping = await tableAdapter.getFieldMapping(connection, tableName, 'idleItems');
    console.log('🔧 字段映射:', fieldMapping);
    
    // 构建查询字段
    const selectFields = tableAdapter.buildSelectFields(fieldMapping);
    console.log('📝 查询字段:', selectFields);
    
    // 测试查询
    const sql = `SELECT ${selectFields} FROM ${tableName} LIMIT 1`;
    console.log('🔍 执行SQL:', sql);
    
    const [rows] = await connection.execute(sql);
    console.log('📊 查询结果:', rows);
    
    if (rows.length > 0) {
      // 转换数据
      const transformed = tableAdapter.transformRow(rows[0], fieldMapping);
      console.log('✨ 转换后的数据:', transformed);
      
      // 检查关键字段
      console.log('\n📋 关键字段检查:');
      console.log(`借用条件: ${transformed.borrowCondition}`);
      console.log(`联系信息: ${transformed.contactInfo}`);
      console.log(`押金: ${transformed.deposit}`);
    }
    
    await connection.end();
    console.log('\n✅ 测试完成！');
    
  } catch (error) {
    console.error('❌ 测试失败:', error.message);
  }
}

testMapping();
